package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.search.service.ApAssociateWordsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author: Administrator
 * CreateTime: 2024/10/9
 * Project: heima-leadnews
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    private final MongoTemplate mongoTemplate;

    /**
     * 关键词联想
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findAssociate(UserSearchDto userSearchDto) {
        // 1.参数检查
        if (userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        // 2.分页查询
        if (userSearchDto.getPageSize() > 20) userSearchDto.setPageSize(20);

        // 3.执行查询
        Query query = Query.query(Criteria.where("associateWords").regex(".*?\\" + userSearchDto.getSearchWords() + ".*"));
        query.limit(userSearchDto.getPageSize());
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(apAssociateWords);
    }
}
